/*
 *  Copyright (c) 2014 ZengYajian
 *
 *  Simple http protocol parser module.
 *  by ZengYajian
 */

#define _GNU_SOURCE
#include <stdio.h>

#include <string.h>
#include <stdlib.h>

#include "http.h"
#include "log/log.h"

/* alloc a request struct, must free by http_request_free() */
struct http_request_t *http_request_alloc(enum request_type type)
{
	struct http_request_t *r;

	r = malloc(sizeof(*r));
	if (!r) {
		_log(ERROR, "out of memory, unable to alloc 'http_request_t'\n");
		return NULL;
	}

	memset(r, 0, sizeof(*r));
	return r;
}

void http_request_free(struct http_request_t *r)
{
	if (!r)
		return;

	if (r->res)
		free(r->res);
	if (r->host)
		free(r->host);

	free(r);
}

/*
 * GET / HTTP/1.1
 * Host: 127.0.0.1:7070
 * User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64; rv:24.0) Gecko/20100101 Firefox/24.0
 * Accept: text/html,application/xhtml+xml,application/xml;q=0.9
 * Accept-Language: zh-cn,zh;q=0.8,en-us;q=0.5,en;q=0.3
 * Accept-Encoding: gzip, deflate
 * Connection: keep-alive
 *
 */

enum request_type http_content_parse(char *content, int size, struct http_request_t *r)
{
	int i;
	char *pstart, *pend;

	/* 1. pre process, remove CF and LF characters */
	for (i=0; i<size; i++) {
		if (content[i] == '\r' || content[i] == '\n') {
			content[i] = '*';
		}
	}

	/* 2. parse the request type */
	if (!strncasecmp(content, "GET ", 4)) {
		_log(DEBUG, "Request 'GET' is accept\n");
		r->type = REQUEST_GET;

		pstart = (char *)(content + strlen("GET "));
		pend = strstr(pstart, " ");
		*pend = '\0';
		asprintf(&r->res, ".%s", pstart);
		_log(DEBUG, "Resource: %s\n", r->res);
	} else if (!strncasecmp(content, "POST ", 4)) {
		_log(DEBUG, "Request 'POST' is accept\n");
		r->type = REQUEST_POST;
	}

	return r->type;
}

